<template>
  <div class="page-wrapper" v-if="config && config.dataSource">
    <div class="toolbar">
      <div class="breadcrumb">
        <a-breadcrumb>
          <a-breadcrumb-item>报表查询</a-breadcrumb-item>
          <a-breadcrumb-item>{{ config.name }}</a-breadcrumb-item>
        </a-breadcrumb>
      </div>

      <a-space>
        <AdvancedSearchPanel
          :fields="searchFields"
          :searchModel="searchModel"
          @search="queryList"
        />
        <a-button type="primary" :loading="loading" @click="queryList">
          <template #icon>
            <SyncOutlined />
          </template>
          刷新
        </a-button>
        <a-button type="primary" @click="exportExcel">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button>
      </a-space>
    </div>
    <div class="container">
      <div class="table">
        <a-table
          bordered
          sticky
          :columns="columns"
          :row-key="(record) => record.id"
          :data-source="dataSource"
          :pagination="config.dataSource.isPaged ? pagination : false"
          :loading="loading"
          @change="handleTableChange"
        >
        </a-table>
      </div>
    </div>
  </div>
  <div v-else>
    <a-skeleton active />
  </div>
</template>

<script lang="ts" setup>
import { IButtonActionsItem, IFormPopupModel, ISerachFieldItem } from "@/types";
import { ReportConfigDto } from "@/api/report/types";
import api from "@/api";
import reportApi from "@/api/report/reportConfig";
import { message, PaginationProps, TableColumnProps } from "ant-design-vue";
import { SortOrder } from "ant-design-vue/es/table/interface";
import { onMounted, reactive, ref, VNode, watch } from "vue";
import { PaginationConfig } from "ant-design-vue/es/pagination";
import { enumName } from "@/plugins/enums";
import { dictionaryName } from "@/plugins/dictionary";
import {
  getEnterpriseName,
  getOrganizeName,
  getUserName,
  getRegionName,
} from "@/plugins/conversion";
import dayjs from "dayjs";

import { Excel, type mergeListType } from "@/helpers/excel";

type IFormatterHandler = (opts: any) => any;
type IResponseItemsHandler = (items: Array<any>) => Array<Record<string, any>>;
type ICustomCellHandler = (
  data: any,
  index: number,
  column: TableColumnProps,
  items: Array<any>
) => any;
const props = defineProps({ code: { type: String, required: true } });

const columns = ref<Array<TableColumnProps>>([]);
const loading = ref(false);
const searchModel = ref<Record<string, any>>({});
const searchFields = ref<Array<ISerachFieldItem>>([]);
const dataSource = ref<Array<any>>([]);

const $app = {
  enumName: enumName,
  dictionaryName: dictionaryName,
  enterpriseName: getEnterpriseName,
  userName: getUserName,
  areaName: getRegionName,
  organizeName: getOrganizeName,
  formatDate: (val: string, format: string) =>
    dayjs(val).format(format || "YYYY-MM-DD"),
  formatNow: (val: string) => dayjs(val).fromNow()
};

/**
 * 分页数据
 */
const pagination: PaginationProps = reactive({
  total: 0,
  current: 1,
  pageSize: 20,
  showTotal: (total, range) => {
    return `共 ${total} 条数据`;
  },
  showSizeChanger: true,
  pageSizeOptions: ["10", "15", "20", "30", "50", "100", "200", "300", "500"],
  onShowSizeChange: (current, pageSize) => (pagination.pageSize = pageSize),
});

/**
 * 报表配置
 */
const config = ref<ReportConfigDto>();
const responseItemsHandler = ref<IResponseItemsHandler>();
const customCellHandler = ref<ICustomCellHandler>();

/**
 * 分页操作处理
 * @param pagination
 * @param filters
 */
const handleTableChange = (pageConfig: PaginationConfig, filters: any) => {
  pagination.current = pageConfig.current;
  queryList();
};

/**
 * 查询数据
 */
const queryList = () => {
  const { remoteUrl, itemsField } = config.value.dataSource;
  console.log("remoteUrl", remoteUrl);
  let model: any = { ...searchModel.value };
  if (config.value.dataSource.isPaged) {
    //启用分页处理
    let { pageSize, current } = pagination;
    let pageIndex = pageSize * ((current || 1) - 1);
    model.maxResultCount = pageSize;
    model.skipCount = pageIndex;
  }
  api.get(remoteUrl, model).then((res) => {
    let items = itemsField ? res[itemsField] : res;
    if (responseItemsHandler.value) {
      dataSource.value = responseItemsHandler.value(items);
    } else {
      dataSource.value = items;
    }
  });
};

/**
 * 导出数据
 */
const exportExcel = () => {
  let header = columns.value.map((x) => x.dataIndex as string);
  let customHeader = columns.value.map((x) => x.title as string);
  let mergeList: mergeListType[] = reactive([]);
  let items = dataSource.value.map((x, i) => {
    let item: any = {};
    columns.value.map((col) => {
      let field = col.dataIndex as string;
      if (field) {
        let value = x[field];
        if (col.customRender) {
          let opts = {
            value,
            text: value,
            record: x,
            index: i,
          } as any;
          item[field] = col.customRender(opts);
        } else {
          item[field] = value;
        }
      }
    });
    return item;
  });
  const excel = new Excel();
  excel.exportExcel({
    name: config.value.name,
    title: config.value.name,
    data: items,
    header,
    customHeader,
    mergeList,
  });
};

/**
 * 加载配置信息
 */
const loadConfig = () => {
  reportApi
    .getForCode(props.code)
    .then((res) => {
      console.log("res", res);
      if (!res) {
        message.error("未找到对应的报表查询配置");
      } else {
        config.value = res;
        loadHandler();
        loadColumns();
        loadQueryModel();
        loadQueryFields();
        queryList();
      }
    })
    .finally(() => {
      loading.value = false;
    });
  loading.value = true;
};

/**
 * 生成默认查询参数
 */
const loadQueryModel = () => {
  config.value.requestOptions.map((item) => {
    searchModel.value[item.name] = item.defaultValue;
  });
};

/**
 * 生成查询字段配置
 */
const loadQueryFields = () => {
  searchFields.value = config.value.requestOptions.map((item) => {
    return {
      label: item.description,
      name: item.name,
      input: item.componentOptions.name,
      props: item.componentOptions.props,
    };
  });
};

/**
 * 加载自定义处理脚本函数
 */
const loadHandler = () => {
  //处理数据集函数
  let { requireHandler, itemsHandler } = config.value.dataSource;
  if (requireHandler) {
    let args = ["items", itemsHandler || "return items;"];
    responseItemsHandler.value = new Function(...args) as any;
  } else {
    responseItemsHandler.value = null;
  }

  //处理自定义单元格合并函数
  let { useCustomCell, customCell } = config.value.reportProps;
  if (useCustomCell) {
    let args = ["data", "index", "column", "items", customCell];
    customCellHandler.value = new Function(...args) as ICustomCellHandler;
  } else {
    customCellHandler.value = null;
  }
};

/**
 * 加载展示列
 */
const loadColumns = () => {
  columns.value = config.value.reportColumns.map((item) => {
    var col: TableColumnProps = {
      dataIndex: item.name,
      title: item.title,
    };
    if (item.width) {
      col.width = item.width;
    }
    if (item.align) {
      col.align = item.align as any;
    }
    if (item.formatter) {
      //格式化函数
      col.customRender = createCustomRender(item.formatter);
    }

    if (customCellHandler.value) {
      col.customCell = (data, index, column) => {
        return customCellHandler.value(data, index, column, dataSource.value);
      };
    }
    return col;
  });
};

/**
 * 创建格式化函数
 * @param content
 */
const createCustomRender = (content: string) => {
  let js = content.trim();
  if (js.indexOf("return ") == -1) {
    js = "return " + js;
  }
  let arg0 = "{$app,value,record,index}";
  let formatter = new Function(arg0, js) as IFormatterHandler;
  return (opt: any) => {
    let data = {
      $app,
      record: opt.record,
      value: opt.value,
      index: opt.index,
    };
    return formatter(data);
  };
};

/**
 * 生成汇总行
 */
const createSummaryRow = () => {};

watch(
  () => props.code,
  () => loadConfig(),
  { immediate: true }
);
</script>

<style lang="less" scoped></style>
